package concurrent.automic;

import com.sun.org.apache.xpath.internal.operations.Bool;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/11/25
 * <p>
 * \* Time: 11:11
 * <p>
 * \* Description:
 * \    基于AtomicBoolean实现一个乐观锁
 */
public class AtomicLock {
    private AtomicBoolean lock = new AtomicBoolean(false);
    private ThreadLocal<Boolean> tl = ThreadLocal.withInitial(()->false);

    private Boolean tryLock() throws InterruptedException {
        boolean b = lock.compareAndSet(false, true);
        if (b) {
            tl.set(true);
        }
        return b;
    }

    private Boolean unLock() {
        if (tl.get()) {
            tl.remove();
            return lock.compareAndSet(true, false);
        } else {
            return false;
        }
    }

    public static class MyThread implements Runnable {

        private int a;

        private AtomicLock lock;

        public MyThread(int a, AtomicLock lock) {
            this.a = a;
            this.lock = lock;
        }

        @Override
        public void run() {
            try {
                if(lock.tryLock()) {
                    Thread.sleep(100);
                    lock.unLock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(a + "---" + Thread.currentThread().getName() + "我在处理");
        }
    }

    public static void main(String[] args) {
        AtomicLock lock = new AtomicLock();
        for (int i = 0; i < 50; i++) {
            new MyThread(i, lock).run();
        }
    }
}
